<?php
/**
 * 卖家实物订单管理
 */

defined('IN_KG') or exit('Access Invalid!');
class store_orderControl extends BaseSellerControl {
    public function __construct() {
        parent::__construct();
        Language::read('member_store_index');
    }

    /**
     * 订单列表
     *
     */
    public function indexOp() {
        $model_order = Model('order');
        if (!$_GET['state_type']) {
            $_GET['state_type'] = 'store_order';
        }
        // $order_list = $model_order->getStoreOrderList($_SESSION['store_id'], $_GET['order_sn'], $_GET['buyer_name'], $_GET['state_type'], $_GET['query_start_date'], $_GET['query_end_date'], $_GET['skip_off'], '*', array('order_goods','order_common','member'));
        $order_list = $model_order->getStoreOrderList($_SESSION['store_id'], $_GET['order_sn'], $_GET['qtype'], $_GET['query'], $_GET['state_type'], $_GET['query_start_date'], $_GET['query_end_date'], $_GET['skip_off'], '*', array('order_goods','order_common','member'));
        $remark_model = Model('order_extra');
        $order_goods_ids = array();
        $order_remarks = $remark_model->findRemark(array_keys($order_list));

        foreach ($order_list as $key => $order) {
            $order_list[$key]['remark'] = $order_remarks[$order['order_id']];
<<<<<<< HEAD

            $order_list[$key]['extend_order_common']['reciver_info']['address'] =  str_replace(' ','，',$order['extend_order_common']['reciver_info']['address']);

=======
            
>>>>>>> 273d61a20916355bd359bbfde6d62910e0852e5a
            foreach ($order['goods_list'] as $k => $v) {
                $order_goods_ids[] = $v['goods_id'];
                if (!strpos('，', $v['goods_spec'])) {
                    continue;
                }
                $spec2 = explode('，', $v['goods_spec']);
                $temp_spec = array();
                foreach ($spec2 as $ks => $vs) {
                    $spec1 = explode('：', $vs)[1];
                    $temp_spec[] = $spec1;
                }
                $order_list[$key]['goods_list'][$k]['spec2'] = substr($v['goods_name'], strpos($v['goods_name'], implode(' ', $temp_spec)));
            }


            /*2017-08-10  增加订单使用的红包优惠信息*/
            foreach ($order['extend_order_common'] as $kk => $vv){
                if ($kk == 'promotion_info'){
                    $data = unserialize($vv);
                    if($data[0][0] == '平台红包'){
                        $code = $data[0][1];
                        preg_match_all('/：(\d+)?/',$code,$result);
                        if(is_numeric($result[1][0])){
                            $pack_title = Model('redpacket')->query(
                                'select rpacket_title,rpacket_desc from shop_redpacket where rpacket_code ='.$result[1][0]
                            );
                            if (!$pack_title){
                                continue;
                            }
                            $data[] = array('红包名称',$pack_title[0]['rpacket_title']);
                            $en_data = serialize($data);
                            $order_list[$key]['extend_order_common'][$kk] = $en_data;
                            //debug($order_list[$key]['extend_order_common'][$kk]);
                        }
                    }
                }
            }

            /*2017-10-16  新需求,隐藏订金订单，订金订单组合尾款订单显示*/
            if($order['order_type'] == 4){
                $groupBuyWhere['deposit_order_id'] = $order['order_id'];
                $groupbuyOrder = Model('groupbuy_orders')->where($groupBuyWhere)->find();

                $groupbuyInfo = Model('groupbuy')->where(array('groupbuy_id' => $groupbuyOrder['groupbuy_id']))->find();

                switch ($order['order_state']){
                    case 20:
                        $order_list[$key]['state_desc'] = '待成团';
                        break;
                    case 10:
                        $order_list[$key]['state_desc'] = '未付尾款';
                        break;
                }

                if (!$groupbuyOrder){
                    continue;
                }

                $paidOrder = Model('orders')->where(array('order_id' => $groupbuyOrder['paid_order_id']))->find();
                if (!$paidOrder){
                    continue;
                }

                //替换订单
                $order_list[$key]['order_id'] = $paidOrder['order_id'];
                $order_list[$key]['order_sn'] = $paidOrder['order_sn'];
                $order_list[$key]['pay_sn'] = $paidOrder['pay_sn'];
                $order_list[$key]['paid_amount'] = $order_list[$key]['order_amount'];
                $order_list[$key]['order_state'] = $paidOrder['order_state'];
                $order_list[$key]['refund_state'] = $paidOrder['refund_state'];
                $order_list[$key]['lock_state'] = $paidOrder['lock_state'];
                $order_list[$key]['paid_order'] = $paidOrder;
                $order_list[$key]['order_type'] = $paidOrder['order_type'];

                $remark = Model('order_extra')->where(array('order_id' => $paidOrder['order_id']))->find();
                $order_list[$key]['remark']['remark'] = $remark['remark'];

                $order_list[$key]['groupbuy_status'] = 1;

                switch ($paidOrder['order_state']){
                    case 20:
                        $order_list[$key]['state_desc'] = '已付尾款';
                        break;
                    case 10:
                        $order_list[$key]['state_desc'] = '未付尾款';
                        break;
                    case 30:
                        $order_list[$key]['state_desc'] = '已发货';
                        break;
                    case 40:
                        $order_list[$key]['state_desc'] = '已收货';
                        break;
                    case 0:
                        $order_list[$key]['state_desc'] = '已取消';
                        break;
                }
                //$order_list[$key]['paid_order'] = $paidOrder;

            }


            /*团购尾款订单*/
            if (!empty($_GET['state_type']) && $order['order_type'] == 5){
                $groupBuyWhere['paid_order_id'] = $order['order_id'];
                $groupbuyOrder = Model('groupbuy_orders')->where($groupBuyWhere)->find();
                //$groupbuyInfo = Model('groupbuy')->where(array('groupbuy_id' => $groupbuyOrder['groupbuy_id']))->find();
                $deposit_order = Model('orders')->where(array('order_id' => $groupbuyOrder['deposit_order_id']))->find();
                $order_list[$key]['paid_order']['order_amount'] = $order_list[$key]['order_amount'];
                $order_list[$key]['order_amount'] = $deposit_order['order_amount'];
                //$order_list[$key]['paid_order'] = $paidOrder;
            }
        }

        

        $all_goods_serials = Model('goods')->table('goods')->field('goods_serial, goods_id')->where(array('goods_id' => array('in', implode(',', $order_goods_ids))))->select();
        $goods_serials = array();
        // $goods_serials = Model('goods')->getGoodsInfo(array('goods_id' => ' in ('.implode(',', $order_goods_ids).') '), 'goods_serial');
        foreach ($all_goods_serials as $key => $serial) {
            $goods_serials[$serial['goods_id']] = $serial['goods_serial'];
        }

        foreach ($order_list as $item => $value){
            if (!empty($value['zengpin_list'][0]['goods_id'])){
                $goods_id  = $value['zengpin_list'][0]['goods_id'];
                $zp_info = Model('goods')->getGoodsInfo(array('goods_id' => $goods_id));
                $order_list[$item]['zengpin_list'][0]['goods_source_name'] = $zp_info['goods_name'];
                $order_list[$item]['zengpin_list'][0]['goods_serial']   = $zp_info['goods_serial'];
            }
        }
        Tpl::output('order_list',$order_list);
        Tpl::output('goods_serials',$goods_serials);
        Tpl::output('show_page',$model_order->showpage());
        self::profile_menu('list',$_GET['state_type']);

        Tpl::showpage('store_order.index');
    }

    /**
     * 2017年2月25日15:32 增加新功能。
     */
    public function exportOp(){
        $model_order = Model('order');
        $condition = $this->_getExportCondition($_SESSION['store_id'], $_GET['order_sn'], $_GET['qtype'], $_GET['query'], $_GET['state_type'], $_GET['query_start_date'], $_GET['query_end_date'], $_GET['skip_off']);
        $condition['order_type'] = array('in',array(1,2,3,5));


        echo "<pre>";
        // 先查询出该导出区域中共有多少订单
        $order_count = $model_order->getExportOrderList($condition, array(), 0,1);
        $page = ceil($order_count/100);
        $export_mode = empty($_GET['finance']) ? 0 : 1;
        $this->_echoExportHeader();
        $this->_echoExportTableHeader($export_mode);
        for ($i=0; $i < $page; $i++) { 
            $list = $model_order->getExportOrderList($condition, array('order_goods','order_common','member'), $i);
            $deal_list = $this->_dealExportOrders($list, array_keys($list));
            // print_r($deal_list);
            $this->_echoExportBody($deal_list, $export_mode);
        }
        echo '</tbody></table>';
        // print_r(Model('order')->getExportOrderList($condition, array(), 1,1));
    }

    /**
     * 处理表单数据。
     * @param  [type] $order_list [description]
     * @param  array  $order_ids  [description]
     * @return [type]             [description]
     */
    private function _dealExportOrders($order_list, $order_ids = array()){
        $express = rkcache('express',true);
        $list = array();

        $remarks = Model('order_extra')->findRemark($order_ids);
        $order_from = array('1'=>'网页', '2'=>'APP', '3'=>'IOS', '4' =>'ANDROID');
        foreach ($order_list as $key => $order) {
            $one = array();
            $ids = array();
            $names = array();
            $one['order_sn'] = $order['order_sn'];
            $one['add_time'] = date("Y-m-d H:i:s",$order['add_time']);
            $one['pay_time'] = +$order['api_pay_time'] != 0 ? date("Y-m-d H:i:s",$order['api_pay_time']) : '';
            $order_goods = array();
            foreach ($order['extend_order_goods'] as $kg => $vg) {
                $ids[] = $vg['goods_id'];
                if (!strpos($vg['goods_spec'], '，')) {
                    $names[] = $vg['goods_spec'].' x'. $vg['goods_num'];
                }else{
                    $spec2 = explode('，', $vg['goods_spec']);
                    $temp_spec = array();
                    foreach ($spec2 as $ks => $vs) {
                        $spec1 = explode('：', $vs)[1];
                        $temp_spec[] = $spec1;
                    }
                    $goods_spec = substr($vg['goods_name'], strpos($vg['goods_name'], implode(' ', $temp_spec)));
                    $names[] = $goods_spec . ' x'. $vg['goods_num'];
                }
                $order_goods[] = array(
                    'goods_name' => $vg['goods_name'],
                    'goods_id' => $vg['goods_id'],
                    'goods_spec' => $vg['goods_spec'],
                    'goods_num' => $vg['goods_num']
                );
            }
            $mansong_goods = Model('order_goods')->where(array('order_id' => $order['order_id'], 'goods_type' => 5))->find();
            if (!empty($mansong_goods)){
                $names[] = '赠品:'.$mansong_goods['goods_name'] .'x 1';
            }

            $one['order_goods'] = $order_goods;
            $one['goods_ids'] = implode('；', $ids);
            $one['goods_name'] = implode('；', $names);
            $one['goods_amount'] = $order['goods_amount'];
            $one['rpt_info'] = $order['rpt_amount'] > 0 ? '红包' : '无';
            $one['rpt_amount'] = $order['rpt_amount'];
            $one['order_amount'] = $order['order_amount'];
            $one['payment_name'] = $order['payment_name'];
            $pay_amount = 0;
            if ($order['order_state'] == 0) {
                $pay_amount = 0;
            }elseif ($order['order_state'] != 40 && $order['payment_code'] == 'offline') {
                $pay_amount = 0;
            }elseif ($order['order_state'] == 40 && $order['payment_code'] == 'offline') {
                $pay_amount = $order['order_amount'] - $order['refund_amount'];
            }else{
                $pay_amount = $order['order_amount'] - $order['refund_amount'];
            }
            $one['pay_amount'] = $pay_amount;
            $one['order_state'] = $order['state_desc'];
            $one['refund_amount'] = $order['refund_amount'];
            $one['reciver_name'] = $order['extend_order_common']['reciver_name'];
            $one['reciver_phone'] = $order['extend_order_common']['reciver_info']['mob_phone'];
            $one['reciver_address'] = $order['extend_order_common']['reciver_info']['area'].' '.$order['extend_order_common']['reciver_info']['street'];
            $one['pay_sn'] = $order['pay_sn'];
            $one['express'] = $express[$order['extend_order_common']['shipping_express_id']]['e_name'];
            $one['express_code'] = $order['shipping_code'];
            $one['order_message'] = $order['extend_order_common']['order_message'];
            // $remark = $remark_model->findRemark($order['order_id']);
            $remark = $remarks[$order['order_id']];
            $one['order_remark'] = $remark['remark'];
            $one['order_from'] = $order_from[$order['order_from']];
            $list[] = $one;
        }
        return $list;
    }

    /**
     * 获取导出搜索条件
     * @param  [type] $store_id         [description]
     * @param  [type] $order_sn         [description]
     * @param  [type] $qtype            [description]
     * @param  [type] $query            [description]
     * @param  [type] $state_type       [description]
     * @param  [type] $query_start_date [description]
     * @param  [type] $query_end_date   [description]
     * @param  [type] $skip_off         [description]
     * @return [type]                   [description]
     */
    private function _getExportCondition($store_id, $order_sn, $qtype, $query, $state_type, $query_start_date, $query_end_date, $skip_off){
        $condition = array();
        $condition['store_id'] = $store_id;
        if (preg_match('/^\d{10,20}$/',$order_sn)) {
            $condition['order_sn'] = $order_sn;
        }
        if ($query != '') {
            $condition[$qtype] = $query;
        }
        $allow_state_array = array('state_new','state_pay','state_send','state_success','state_cancel');
        if (in_array($state_type, $allow_state_array)) {
            $condition['order_state'] = str_replace($allow_state_array,
                    array(ORDER_STATE_NEW,ORDER_STATE_PAY,ORDER_STATE_SEND,ORDER_STATE_SUCCESS,ORDER_STATE_CANCEL), $state_type);
        } else {
            if ($state_type != 'state_notakes') {
                $state_type = 'store_order';
            }
        }
        $if_start_date = preg_match('/^20\d{2}-\d{2}-\d{2}$/',$query_start_date);
        $if_end_date = preg_match('/^20\d{2}-\d{2}-\d{2}$/',$query_end_date);
        $start_unixtime = $if_start_date ? strtotime($query_start_date) : null;
        $end_unixtime = $if_end_date ? strtotime($query_end_date): null;
        if ($start_unixtime || $end_unixtime) {
            $condition['add_time'] = array('time',array($start_unixtime,$end_unixtime));
        }

        if ($skip_off == 1) {
            $condition['order_state'] = array('neq',ORDER_STATE_CANCEL);
        }

        if ($state_type == 'state_new') {
            $condition['chain_code'] = 0;
        }
        if ($state_type == 'state_pay') {
            $condition['chain_code'] = 0;
        }
        if ($state_type == 'state_notakes') {
            $condition['order_state'] = array('in',array(ORDER_STATE_NEW,ORDER_STATE_PAY));
            $condition['chain_code'] = array('gt',0);
        }
        return $condition;
    }

    private function _echoExportBody($order_list, $mode){
        if ($mode) {
            foreach ($order_list as $ko => $vo){
                $goods_count = count($vo['order_goods']);
                echo'<tr>
                    <td rowspan="'.$goods_count.'">'.$vo['order_sn'].',</td>
                    <td rowspan="'.$goods_count.'">'.$vo['pay_time'].'</td>
                    <td rowspan="1">'.$vo['order_goods'][0]['goods_id'].'</td>
                    <td rowspan="1">'.$vo['order_goods'][0]['goods_name'].'</td>
                    <td rowspan="1">'.$vo['order_goods'][0]['goods_spec'].'</td>
                    <td rowspan="1">'.$vo['order_goods'][0]['goods_num'].'</td>
                    <td rowspan="'.$goods_count.'">'.$vo['goods_amount'].'</td>
                    <td rowspan="'.$goods_count.'">'.$vo['rpt_info'].'</td>
                    <td rowspan="'.$goods_count.'">'.$vo['rpt_amount'].'</td>
                    <td rowspan="'.$goods_count.'">'.$vo['order_amount'].'</td>
                    <td rowspan="'.$goods_count.'">'.$vo['pay_amount'].'</td>
                    <td rowspan="'.$goods_count.'">'.$vo['payment_name'].'</td>
                    <td rowspan="'.$goods_count.'">'.$vo['order_state'].'</td>
                    <td rowspan="'.$goods_count.'">'.$vo['order_from'].'</td>
                    <td rowspan="'.$goods_count.'">'.$vo['refund_amount'].'</td>
                    <td rowspan="'.$goods_count.'">'.$vo['reciver_name'].'</td>
                    <td rowspan="'.$goods_count.'">'.$vo['reciver_phone'].'</td>
                    <td rowspan="'.$goods_count.'">'.$vo['reciver_address'].'</td>
                    <td rowspan="'.$goods_count.'">'.$vo['pay_sn'].',</td>
                    <td rowspan="'.$goods_count.'">'.$vo['express'].'</td>
                    <td rowspan="'.$goods_count.'">'.$vo['express_code'].',</td>
                </tr>';
                for ($i=1; $i < $goods_count; $i++) { 
                    echo '<tr>
                    <td rowspan="1">'.$vo['order_goods'][$i]['goods_id'].'</td>
                    <td rowspan="1">'.$vo['order_goods'][$i]['goods_name'].'</td>
                    <td rowspan="1">'.$vo['order_goods'][$i]['goods_spec'].'</td>
                    <td rowspan="1">'.$vo['order_goods'][$i]['goods_num'].'</td>
                </tr>';
                }
            }
        }else{
            foreach ($order_list as $ko => $vo){
                echo'<tr>
                    <td>'.$vo['order_sn'].'</td>
                    <td>'.$vo['add_time'].'</td>
                    <td>'.$vo['pay_time'].'</td>
                    <td>'.$vo['goods_ids'].'</td>
                    <td>'.$vo['goods_name'].'</td>
                    <td>'.$vo['order_amount'].'</td>
                    <td>'.$vo['payment_name'].'</td>
                    <td>'.$vo['order_state'].'</td>
                    <td>'.$vo['order_from'].'</td>
                    <td>'.$vo['reciver_name'].'</td>
                    <td>'.$vo['reciver_phone'].'</td>
                    <td>'.$vo['reciver_address'].'</td>
                    <td>'.$vo['express'].'</td>
                    <td>'.$vo['express_code'].'</td>
                    <td>'.$vo['order_message'].'</td>
                    <td>'.$vo['order_remark'].'</td>
                </tr>';
            }
        }
    }

    private function _echoExportHeader(){
        $type = str_replace(array('store_order', 'state_new','state_pay','state_send','state_success','state_cancel'),
                    array('所有','待付款','待发货','已发货','已完成','已取消'), $_GET['state_type']);
        $filename = $_GET['query_start_date'] .' 到 '.$_GET['query_end_date'] ."$type订单";

        // echo "<pre >";print_r($order_list);echo "</pre>";die();
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Content-type:application/vnd.ms-excel");  
        header("Content-Disposition:attachment;filename=".$filename.".xls");
        header("Pragma: no-cache");
        header("Expires: 0");
    }

    private function _echoExportTableHeader($mode){
        if ($mode) {
            echo "<table border='1'>
                <thead>
                    <tr>
                        <th>订单编号</th>
                        <th>付款时间</th>
                        <th>货号</th>
                        <th>商品名称</th>
                        <th>规格/属性</th>
                        <th>数量</th>
                        <th>买家应付金额</th>
                        <th>减免方式</th>
                        <th>减免金额</th>
                        <th>订单总金额</th>
                        <th>买家实付金额</th>
                        <th>付款方式</th>
                        <th>订单状态</th>
                        <th>订单来源</th>
                        <th>退款金额</th>
                        <th>姓名</th>
                        <th>电话</th>
                        <th>地址</th>
                        <th>付款单号</th>
                        <th>物流公司</th>
                        <th>快递单号</th>
                    </tr>
                </thead>
                <tbody>";
        }else{
            echo "<table border='1'>
                <thead>
                    <tr>
                        <th>订单编号</th>
                        <th>下单时间</th>
                        <th>付款时间</th>
                        <th>货号</th>
                        <th>商品名称（包含规格属性数量）</th>
                        <th>商品总价</th>
                        <th>付款方式</th>
                        <th>订单状态</th>
                        <th>订单来源</th>
                        <th>姓名</th>
                        <th>电话</th>
                        <th>地址</th>
                        <th>物流公司</th>
                        <th>快递单号</th>
                        <th>买家留言</th>
                        <th>卖家备注</th>
                    </tr>
                </thead>
                <tbody>";
        }
    }


    public function export_oldOp() {
        $model_order = Model('order');
        if (!$_GET['state_type']) {
            $_GET['state_type'] = 'store_order';
        }
        // $order_list = $model_order->getStoreOrderList($_SESSION['store_id'], $_GET['order_sn'], $_GET['buyer_name'], $_GET['state_type'], $_GET['query_start_date'], $_GET['query_end_date'], $_GET['skip_off'], '*', array('order_goods','order_common','member'));
        $order_list = $model_order->getStoreOrderList($_SESSION['store_id'], $_GET['order_sn'], $_GET['qtype'], $_GET['query'], $_GET['state_type'], $_GET['query_start_date'], $_GET['query_end_date'], $_GET['skip_off'], '*', array('order_goods','order_common','member'), null, 200);
        $remark_model = Model('order_extra');
        $express = rkcache('express',true);
        $list = array();
        foreach ($order_list as $key => $order) {
            $one = array();
            $ids = array();
            $names = array();
            $one['pay_sn'] = $order['pay_sn'];
            $one['add_time'] = date("Y-m-d H:i:s",$order['add_time']);
            $one['pay_time'] = +$order['api_pay_time'] != 0 ? date("Y-m-d H:i:s",$order['api_pay_time']) : '';
            foreach ($order['extend_order_goods'] as $kg => $vg) {
                $ids[] = $vg['goods_id'];
                if (!strpos($vg['goods_spec'], '，')) {
                    $names[] = $vg['goods_spec'] . ' x'. $vg['goods_num'];
                }else{
                    $spec2 = explode('，', $vg['goods_spec']);
                    $temp_spec = array();
                    foreach ($spec2 as $ks => $vs) {
                        $spec1 = explode('：', $vs)[1];
                        $temp_spec[] = $spec1;
                    }
                    $names[] = substr($vg['goods_name'], strpos($vg['goods_name'], implode(' ', $temp_spec))) . ' x'. $vg['goods_num'];
                }
            }
            $one['goods_ids'] = implode('；', $ids);
            $one['goods_name'] = implode('；', $names);
            $one['order_amount'] = $order['order_amount'];
            $one['order_state'] = $order['state_desc'];
            $one['payment_name'] = $order['payment_name'];
            $one['reciver_name'] = $order['extend_order_common']['reciver_name'];
            $one['reciver_phone'] = $order['extend_order_common']['reciver_info']['mob_phone'];
            $one['reciver_address'] = $order['extend_order_common']['reciver_info']['area'].' '.$order['extend_order_common']['reciver_info']['street'];
            $one['express'] = $express[$order['extend_order_common']['shipping_express_id']]['e_name'];
            $one['express_code'] = $order['shipping_code'];
            $one['order_message'] = $order['extend_order_common']['order_message'];
            $remark = $remark_model->findRemark($order['order_id']);
            $one['order_remark'] = $remark['remark'];
            $list[] = $one;
        }

        $type = str_replace(array('store_order', 'state_new','state_pay','state_send','state_success','state_cancel'),
                    array('所有','待付款','待发货','已发货','已完成','已取消'), $_GET['state_type']);
        $filename = $_GET['query_start_date'] .' 到 '.$_GET['query_end_date'] ."$type订单";

        // echo "<pre >";print_r($order_list);echo "</pre>";die();
        header("Content-type:application/octet-stream");
        header("Accept-Ranges:bytes");
        header("Content-type:application/vnd.ms-excel");  
        header("Content-Disposition:attachment;filename=".$filename.".xls");
        header("Pragma: no-cache");
        header("Expires: 0");
        echo "<table border='1'>
            <thead>
                <tr>
                    <th>订单编号</th>
                    <th>下单时间</th>
                    <th>付款时间</th>
                    <th>货号</th>
                    <th>商品名称（包含规格属性数量）</th>
                    <th>商品总价</th>
                    <th>付款方式</th>
                    <th>订单状态</th>
                    <th>姓名</th>
                    <th>电话</th>
                    <th>地址</th>
                    <th>物流公司</th>
                    <th>快递单号</th>
                    <th>买家留言</th>
                    <th>卖家备注</th>
                </tr>
            </thead>
            <tbody>";
        foreach ($list as $ko => $vo){
            echo'<tr>
                <td>'.$vo['pay_sn'].'</td>
                <td>'.$vo['add_time'].'</td>
                <td>'.$vo['pay_time'].'</td>
                <td>'.$vo['goods_ids'].'</td>
                <td>'.$vo['goods_name'].'</td>
                <td>'.$vo['order_amount'].'</td>
                <td>'.$vo['payment_name'].'</td>
                <td>'.$vo['order_state'].'</td>
                <td>'.$vo['order_from'].'</td>
                <td>'.$vo['reciver_name'].'</td>
                <td>'.$vo['reciver_phone'].'</td>
                <td>'.$vo['reciver_address'].'</td>
                <td>'.$vo['express'].'</td>
                <td>'.$vo['express_code'].'</td>
                <td>'.$vo['order_message'].'</td>
                <td>'.$vo['order_remark'].'</td>
            </tr>';
        }
        echo '</tbody></table>';
    }

    /**
     * 卖家订单详情
     *
     */
    public function show_orderOp() {
        Language::read('member_member_index');
        $order_id = intval($_GET['order_id']);
        if ($order_id <= 0) {
            showMessage(Language::get('wrong_argument'),'','html','error');
        }
        $model_order = Model('order');
        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['store_id'] = $_SESSION['store_id'];
        $order_info = $model_order->getOrderInfo($condition,array('order_common','order_goods','member'));
        if (empty($order_info)) {
            showMessage(Language::get('store_order_none_exist'),'','html','error');
        }

        //取得订单其它扩展信息
        $model_order->getOrderExtendInfo($order_info);

        $model_refund_return = Model('refund_return');
        $order_list = array();
        $order_list[$order_id] = $order_info;
        $order_list = $model_refund_return->getGoodsRefundList($order_list,1);//订单商品的退款退货显示
        $order_info = $order_list[$order_id];
        $refund_all = $order_info['refund_list'][0];
        if (!empty($refund_all) && $refund_all['seller_state'] < 3) {//订单全部退款商家审核状态:1为待审核,2为同意,3为不同意
            Tpl::output('refund_all',$refund_all);
        }

        //显示锁定中
        $order_info['if_lock'] = $model_order->getOrderOperateState('lock',$order_info);

        //显示调整费用
        $order_info['if_modify_price'] = $model_order->getOrderOperateState('modify_price',$order_info);

        //显示取消订单
        $order_info['if_store_cancel'] = $model_order->getOrderOperateState('store_cancel',$order_info);

        //显示发货
        $order_info['if_store_send'] = $model_order->getOrderOperateState('store_send',$order_info);

        //显示物流跟踪
        $order_info['if_deliver'] = $model_order->getOrderOperateState('deliver',$order_info);

        //显示系统自动取消订单日期
        if ($order_info['order_state'] == ORDER_STATE_NEW) {
            $order_info['order_cancel_day'] = $order_info['add_time'] + ORDER_AUTO_CANCEL_TIME * 3600;
        }

        //显示快递信息
        if ($order_info['shipping_code'] != '') {
            $express = rkcache('express',true);
            $order_info['express_info']['e_code'] = $express[$order_info['extend_order_common']['shipping_express_id']]['e_short'];
            $order_info['express_info']['e_name'] = $express[$order_info['extend_order_common']['shipping_express_id']]['e_name'];
            $order_info['express_info']['e_url'] = $express[$order_info['extend_order_common']['shipping_express_id']]['e_url'];
        }

        //显示系统自动收获时间
        if ($order_info['order_state'] == ORDER_STATE_SEND) {
            $order_info['order_confirm_day'] = $order_info['delay_time'] + ORDER_AUTO_RECEIVE_DAY * 24 * 3600;
        }

        //取得订单操作日志
        $order_log_list = $model_order->getOrderLogList(array('order_id'=>$order_info['order_id']),'log_id asc');
        Tpl::output('order_log_list',$order_log_list);

        //如果订单已取消，取得取消原因、时间，操作人
        if ($order_info['order_state'] == ORDER_STATE_CANCEL) {
            $last_log = end($order_log_list);
            if ($last_log['log_orderstate'] == ORDER_STATE_CANCEL) {
                $order_info['close_info'] = $last_log;
            }
        }
        //查询消费者保障服务
        if (C('contract_allow') == 1) {
            $contract_item = Model('contract')->getContractItemByCache();
        }
        foreach ($order_info['extend_order_goods'] as $value) {
            $value['image_60_url'] = cthumb($value['goods_image'], 60, $value['store_id']);
            $value['image_240_url'] = cthumb($value['goods_image'], 240, $value['store_id']);
            $value['goods_type_cn'] = orderGoodsType($value['goods_type']);
            $value['goods_url'] = urlShop('goods','index',array('goods_id'=>$value['goods_id']));
            //处理消费者保障服务
            if (trim($value['goods_contractid']) && $contract_item) {
                $goods_contractid_arr = explode(',',$value['goods_contractid']);
                foreach ((array)$goods_contractid_arr as $gcti_v) {
                    $value['contractlist'][] = $contract_item[$gcti_v];
                }
            }
            if ($value['goods_type'] == 5) {
                $order_info['zengpin_list'][] = $value;
            } else {
                $order_info['goods_list'][] = $value;
            }
        }

        if (empty($order_info['zengpin_list'])) {
            $order_info['goods_count'] = count($order_info['goods_list']);
        } else {
            $order_info['goods_count'] = count($order_info['goods_list']) + 1;
        }

        foreach ($order_info['extend_order_goods'] as $gk => $gv) {
            if (!strpos('，', $gv['goods_spec'])) {
                continue;
            }
            $spec2 = explode('，', $gv['goods_spec']);
            $temp_spec = array();
            foreach ($spec2 as $ks => $vs) {
                $spec1 = explode('：', $vs)[1];
                $temp_spec[] = $spec1;
            }
            $order_info['extend_order_goods'][$gk]['goods_spec'] = substr($gv['goods_name'], strpos($gv['goods_name'], implode(' ', $temp_spec)));
        }

        Tpl::output('order_info',$order_info);

        //发货信息
        if (!empty($order_info['extend_order_common']['daddress_id'])) {
            $daddress_info = Model('daddress')->getAddressInfo(array('address_id'=>$order_info['extend_order_common']['daddress_id']));
            Tpl::output('daddress_info',$daddress_info);
        }

        if ($order_info['order_type'] == 5){
            $groupbuy_order = Model('groupbuy')->where(array('paid_order_id' => $order_info['order_id']))->find();
            $deposit_order = Model('orders')->where(array('order_id' => $groupbuy_order['deposit_order_id']))->find();
            $order_info['paid_amount'] = $deposit_order['order_amount'];
        }

        /**
         * 2017-2-14 17:31新需求，增加订单备注功能
         */
        $order_remark = Model('order_extra')->findRemark($order_id);
        Tpl::output('order_remark',$order_remark);

        Tpl::showpage('store_order.show');
    }

    /**
     * 添加备注
     * @return [type] [description]
     */
    public function change_remarkOp(){
        $order_id   = intval($_GET['order_id']);
        $model = Model('order_extra');
        if(!chksubmit()) {
            $remark = $model->findRemark($order_id);
            Tpl::output('order_id',$order_id);
            Tpl::output('remark',$remark);
            Tpl::showpage('store_order.remark','null_layout');
        }else{
            $remark = $_POST['remark'];
            $new = $_POST['new'];
            $dateline = time();
            if (empty($new)) {
                $res = $model->updateRemark($order_id, array('dateline' => $dateline, 'remark' => $remark));
            }else{
                $res = $model->addRemark(array('order_id' => $order_id, 'dateline' => $dateline, 'remark' => $remark));
            }
            if ($res) {
                showDialog('备注成功','reload','succ',empty($_GET['inajax']) ?'':'CUR_DIALOG.close();');
            }else{
                showDialog('备注失败','','error',empty($_GET['inajax']) ?'':'CUR_DIALOG.close();');
            }
        }
    }

    /**
     * 卖家订单状态操作
     *
     */
    public function change_stateOp() {
        $state_type = $_GET['state_type'];
        $order_id   = intval($_GET['order_id']);

        $model_order = Model('order');
        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['store_id'] = $_SESSION['store_id'];
        $order_info = $model_order->getOrderInfo($condition);

        //取得其它订单类型的信息
        $model_order->getOrderExtendInfo($order_info);

        if ($_GET['state_type'] == 'order_cancel') {
            $result = $this->_order_cancel($order_info,$_POST);
        } elseif ($_GET['state_type'] == 'modify_price') {
            $result = $this->_order_ship_price($order_info,$_POST);
        } elseif ($_GET['state_type'] == 'spay_price') {
			$result = $this->_order_spay_price($order_info,$_POST);
    		}
	
        if (!$result['state']) {
            showDialog($result['msg'],'','error',empty($_GET['inajax']) ?'':'CUR_DIALOG.close();',5);
        } else {
            showDialog($result['msg'],'reload','succ',empty($_GET['inajax']) ?'':'CUR_DIALOG.close();');
        }
    }

    /**
     * 取消订单
     * @param unknown $order_info
     */
    private function _order_cancel($order_info, $post) {
        $model_order = Model('order');
        $logic_order = Logic('order');
        if(!chksubmit()) {
            Tpl::output('order_info',$order_info);
            Tpl::output('order_id',$order_info['order_id']);
            Tpl::showpage('store_order.cancel','null_layout');
            exit();
         } else {
             $if_allow = $model_order->getOrderOperateState('store_cancel',$order_info);
             if (!$if_allow) {
                 return callback(false,'无权操作');
             }
             /**
             * 2017年2月18日16:42 关闭取消订单时间。
             */
             /*if (TIMESTAMP - 86400 < $order_info['api_pay_time']) {
                 $_hour = ceil(($order_info['api_pay_time']+86400-TIMESTAMP)/3600);
                 return callback(false,'该订单曾尝试使用第三方支付平台支付，须在'.$_hour.'小时以后才可取消');

             }*/
             $msg = $post['state_info1'] != '' ? $post['state_info1'] : $post['state_info'];
             if ($order_info['order_type'] == 2) {
                 //预定订单
                 return Logic('order_book')->changeOrderStateCancel($order_info,'seller',$_SESSION['seller_name'], $msg);
             } else {
                 $cancel_condition = array();
                 if ($order_info['payment_code'] != 'offline') {
                     $cancel_condition['order_state'] = ORDER_STATE_NEW;
                 }
                 return $logic_order->changeOrderStateCancel($order_info,'seller',$_SESSION['seller_name'], $msg,true,$cancel_condition);
             }
         }
    }

    /**
     * 修改运费
     * @param unknown $order_info
     */
    private function _order_ship_price($order_info, $post) {
        $model_order = Model('order');
        $logic_order = Logic('order');
        if(!chksubmit()) {
            Tpl::output('order_info',$order_info);
            Tpl::output('order_id',$order_info['order_id']);
            Tpl::showpage('store_order.edit_price','null_layout');
            exit();
        } else {
            $if_allow = $model_order->getOrderOperateState('modify_price',$order_info);
            if (!$if_allow) {
                return callback(false,'无权操作');
            }
            return $logic_order->changeOrderShipPrice($order_info,'seller',$_SESSION['seller_name'],$post['shipping_fee']);
        }

    }
	/**
	 * 修改商品价格
	 * @param unknown $order_info
	 */
	private function _order_spay_price($order_info, $post) {
        $model_order = Model('order');
	    $logic_order = Logic('order');
	    if(!chksubmit()) {
	        Tpl::output('order_info',$order_info);
	        Tpl::output('order_id',$order_info['order_id']);
            Tpl::showpage('store_order.edit_spay_price','null_layout');
            exit();
        } else {
            $if_allow = $model_order->getOrderOperateState('spay_price',$order_info);
            if (!$if_allow) {
                return callback(false,'无权操作');
            }
            return $logic_order->changeOrderSpayPrice($order_info,'seller',$_SESSION['member_name'],$post['goods_amount']); 
	    }
	}

    /**
     * 打印发货单
     */
    public function order_printOp() {
        Language::read('member_printorder');

        $order_id   = intval($_GET['order_id']);
        if ($order_id <= 0){
            showMessage(Language::get('wrong_argument'),'','html','error');
        }
        $order_model = Model('order');
        $condition['order_id'] = $order_id;
        $condition['store_id'] = $_SESSION['store_id'];
        $order_info = $order_model->getOrderInfo($condition,array('order_common','order_goods'));
        if (empty($order_info)){
            showMessage(Language::get('member_printorder_ordererror'),'','html','error');
        }
        Tpl::output('order_info',$order_info);

        //卖家信息
        $model_store    = Model('store');
        $store_info     = $model_store->getStoreInfoByID($order_info['store_id']);
        if (!empty($store_info['store_label'])){
            if (file_exists(BASE_UPLOAD_PATH.DS.ATTACH_STORE.DS.$store_info['store_label'])){
                $store_info['store_label'] = UPLOAD_SITE_URL.DS.ATTACH_STORE.DS.$store_info['store_label'];
            }else {
                $store_info['store_label'] = '';
            }
        }
        if (!empty($store_info['store_stamp'])){
            if (file_exists(BASE_UPLOAD_PATH.DS.ATTACH_STORE.DS.$store_info['store_stamp'])){
                $store_info['store_stamp'] = UPLOAD_SITE_URL.DS.ATTACH_STORE.DS.$store_info['store_stamp'];
            }else {
                $store_info['store_stamp'] = '';
            }
        }
        Tpl::output('store_info',$store_info);

        //订单商品
        $model_order = Model('order');
        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['store_id'] = $_SESSION['store_id'];
        $goods_new_list = array();
        $goods_all_num = 0;
        $goods_total_price = 0;
        if (!empty($order_info['extend_order_goods'])){
            $goods_count = count($order_goods_list);
            $i = 1;
            foreach ($order_info['extend_order_goods'] as $k => $v){
                $v['goods_name'] = str_cut($v['goods_name'],100);
                $goods_all_num += $v['goods_num'];
                $v['goods_all_price'] = ncPriceFormat($v['goods_num'] * $v['goods_price']);
                $goods_total_price += $v['goods_all_price'];
                $goods_new_list[ceil($i/4)][$i] = $v;
                $i++;
            }
        }
        //优惠金额
        $promotion_amount = $goods_total_price - $order_info['goods_amount'];
        //运费
        $order_info['shipping_fee'] = $order_info['shipping_fee'];
        Tpl::output('promotion_amount',$promotion_amount);
        Tpl::output('goods_all_num',$goods_all_num);
        Tpl::output('goods_total_price',ncPriceFormat($goods_total_price));
        Tpl::output('goods_list',$goods_new_list);
        Tpl::showpage('store_order.print',"null_layout");
    }

    /**
     * 用户中心右边，小导航
     *
     * @param string    $menu_type  导航类型
     * @param string    $menu_key   当前导航的menu_key
     * @return
     */
    private function profile_menu($menu_type='',$menu_key='') {
        Language::read('member_layout');
        switch ($menu_type) {
            case 'list':
            $menu_array = array(
            array('menu_key'=>'store_order',        'menu_name'=>Language::get('nc_member_path_all_order'), 'menu_url'=>'index.php?control=store_order'),
            array('menu_key'=>'state_new',          'menu_name'=>Language::get('nc_member_path_wait_pay'),  'menu_url'=>'index.php?control=store_order&op=index&state_type=state_new'),
            array('menu_key'=>'state_pay',          'menu_name'=>Language::get('nc_member_path_wait_send'), 'menu_url'=>'index.php?control=store_order&op=store_order&state_type=state_pay'),
            // array('menu_key'=>'state_notakes',      'menu_name'=>'待自提', 'menu_url'=>'index.php?control=store_order&op=store_order&state_type=state_notakes'),
            array('menu_key'=>'state_send',         'menu_name'=>Language::get('nc_member_path_sent'),      'menu_url'=>'index.php?control=store_order&op=index&state_type=state_send'),
            array('menu_key'=>'state_success',      'menu_name'=>Language::get('nc_member_path_finished'),  'menu_url'=>'index.php?control=store_order&op=index&state_type=state_success'),
            array('menu_key'=>'state_cancel',       'menu_name'=>Language::get('nc_member_path_canceled'),  'menu_url'=>'index.php?control=store_order&op=index&state_type=state_cancel'),
            );
            break;
        }
        Tpl::output('member_menu',$menu_array);
        Tpl::output('menu_key',$menu_key);
    }

    private function wl($msg,$path = 'order') {
        $file = $_SERVER['DOCUMENT_ROOT'].'/data/log/debug/'.$path.'-'.date('Ymd',time()) . '.log';
        !is_dir(dirname($file)) && mkdir(dirname($file), 0777, true);
        $handle = fopen($file, 'a');
        flock($handle, LOCK_EX);
        fwrite($handle, sprintf("%s \r\n %s \r\n", date('Y-m-d H:i:s',time()), print_r($msg,true)));
        flock($handle, LOCK_UN);
        fclose($handle);
    }

}
